package org.dengyiqian.customer;

import cn.hutool.core.lang.Validator;
import lombok.extern.slf4j.Slf4j;
import org.dengyiqian.client.FraudReviewResponse;
import org.dengyiqian.client.FraudService;
import org.dengyiqian.client.NotificationRequest;
import org.dengyiqian.customer.exception.ApiException;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@Slf4j
public record CustomerService(CustomerRepository customerRepository,
                              FraudService fraudService,
                              RabbitMQProducer rabbitMQProducer,
                              NotificationConfig notificationMQConfig) {

    public void registerCustomer(CustomerRegistryRequest request) {
        // 利用上面的参数构造一个Customer对象
        Customer customer = Customer.builder()
                .name(request.name())
                .email(request.email())
                .build();

        // 检查email是否有效
        if (request.email() == null || !Validator.isEmail(request.email())) {
            log.error("new customer registration: email地址无效");
        }
        // 检查email是否已经注册
        // 提示：先思考如何编写sql，再考虑CustomerRepository中如何实现
        Optional<Customer> existEmail = customerRepository.findByEmail(customer.getEmail());
        if (!existEmail.isEmpty()) {
            // 注册失败
            log.info("new customer registration: 注册失败 {}, 邮箱已存在", customer);
            throw new ApiException("Email地址已经注册");
        }
        // 调用fraud服务，检查要注册的用户是否有征信问题
        FraudReviewResponse fraudReviewResponse = fraudService.isFraudster(customer.getEmail());
        if (fraudReviewResponse.isFraudster()) {
            throw new ApiException("用户可能存在征信问题");
        }
        // 注册成功存入customer数据库
        customerRepository.saveAndFlush(customer);
        log.info("new customer registration: 注册成功 {}", customer);

        // 注册成功发送通知
        NotificationRequest notificationRequest = new NotificationRequest(
                "尊敬的 "+ customer.getName() + ", 欢迎您选择Example银行。",
                customer.getEmail(),
                customer.getId());
        rabbitMQProducer.publish(notificationRequest,
                notificationMQConfig.getInternalExchange(),
                notificationMQConfig.getInternalNotificationRoutingKey());
    }
}